import { streamCompletion, generateId, getOpenAIKey } from "./functions.js"
import { DEBUG, MODERATION } from "./config.js";
import { requestCompletionsStream, requestChatCompletionsStream } from "./request.js"

/*
req.data: {
    "model": "gpt-3.5-turbo",
    "max_tokens": 100,
    "messages": [
        {
            "role": "system",
            "content": "You are an helpful assistant."
        },
        {
            "role": "user",
            "content": "Who are you?"
        }
    ]
}
*/
export async function completions(req, callback) {
    if (req.stream) {
        try {
            const request = req.messages ? requestChatCompletionsStream : requestCompletionsStream
            //delete req.stream
            const response = await request( req )
            if( response.status){
                for await (const message of streamCompletion(response.response.data)) {
                    try {
                        const parsed = JSON.parse(message);
                        delete parsed.id;
                        delete parsed.created;
                        console.log(`data: ${JSON.stringify(parsed)}\n\n`);
                        callback && callback( parsed )
                    } catch (error) {
                        console.error("Could not JSON parse stream message", message, error);
                    }
                }
            }else{
                callback && callback( {error: true, e: response.error.error} )
            }
        } catch (error) {
            if (DEBUG) console.error("requestCompletionsStream error:",  error);
            callback && callback( {error: true, e: error} )
        }
    }
}